#!/usr/bin/python
# -*- coding: UTF-8 -*-

import cv2
import sys
import colorsys
import os
import numpy as np
import qdarkstyle
from PyQt5.QtWidgets import *
from PyQt5.QtGui import QIcon
import Road_Detection as rd
from PIL import Image, ImageFont, ImageDraw
from PyQt5 import QtCore, QtGui, QtWidgets
from detect import Ui_MainWindow  # 加载我们的布局



class MymainWindow(QMainWindow, Ui_MainWindow):
    def __init__(self, *args, **kwargs):
        super(MymainWindow, self).__init__(*args, **kwargs)
        self.setupUi(self)  # 初始化ui
        self.is_cap = True
        self.showimage.setScaledContents(True)
        self.showimage_2.setScaledContents(True)
        self.showimage_3.setScaledContents(True)
        self.timer_camera = QtCore.QTimer()  # 定义定时器，用于控制显示视频的帧率
        self.cap = cv2.VideoCapture()  # 视频流
        self.openimage.clicked.connect(self.button_open_image_click)
        self.pushButton.clicked.connect(self.button_open_camera_clicked)
        self.timer_camera.timeout.connect(self.show_camera)
        self.pushButton_exit.clicked.connect(self.close_timer)
        self.pushButton_exit_2.clicked.connect(self.close)
        self.btn_video.clicked.connect(self.open_video)
        self.showimage.setScaledContents(True)
        self.setWindowIcon(QIcon('src/icon.png'))
        self.showimage.setText('基于深度学习的车道线检测')

    def close_timer(self):
        self.cap.release()
        self.showimage.clear()
        self.timer_camera.stop()
        self.showimage_2.setText('处理后视频显示区域')
        self.showimage_3.setText('未处理视频显示区域')
        self.showimage.setText('基于深度学习的车道线检测')

    def open_video(self):
        self.is_cap = False
        self.video_path, _ = QFileDialog.getOpenFileName(self, '选择视频', r'C', 'Image files(*.avi *.mp4)')
        self.camera_clicked()

        # 定义定时器

    def button_open_camera_clicked(self):
        self.is_cap = True
        self.camera_clicked()

    def camera_clicked(self):

        if self.timer_camera.isActive() == False:  # 若定时器未启动
            if self.is_cap:
                flag = self.cap.open(0)  # 参数是0，表示打开笔记本的内置摄像头，参数是视频文件路径则打开视频
            else:
                flag = self.cap.open(self.video_path)
            if flag == False:  # flag表示open()成不成功
                msg = QtWidgets.QMessageBox.warning(self, 'warning', "请检查相机于电脑是否连接正确",
                                                    buttons=QtWidgets.QMessageBox.Ok)
            else:
                self.timer_camera.start(30)  # 定时器开始计时30ms，结果是每过30ms从摄像头中取一帧显示
        else:
            self.timer_camera.stop()  # 关闭定时器
            self.cap.release()  # 释放视频流
            self.showimage.clear()  # 清空视频显示区域
        # 显示摄像头画面

    def show_camera(self):
        try:
            flag, frame = self.cap.read()  # 从视频流中读取
            self.road_detect_one(frame)
        except:
            self.close_timer()
            QMessageBox.warning(self, '提示', '视频播放完毕！', QMessageBox.Ok)

    def button_open_image_click(self):
        imgName, imgType = QFileDialog.getOpenFileName(self, "打开图片", "", "*.jpg;;*.png;;All Files(*)")
        image = cv2.imread(imgName)
        # print(type(image))
        self.road_detect_one(image)

    def road_detect_one(self, image):
        image = cv2.resize(image, (640, 480))
        result, lane_image, image = rd.detect_image(image)
        result = cv2.cvtColor(result, cv2.COLOR_BGR2RGB)  # 视频色彩转换回RGB，这样才是现实的颜色
        showImage = QtGui.QImage(result.data, result.shape[1], result.shape[0],
                                 QtGui.QImage.Format_RGB888)  # 把读取到的视频数据变成QImage形式
        self.showimage.setPixmap(QtGui.QPixmap.fromImage(showImage))  # 往显示视频的Label里 显示QImage

        lane_image = cv2.cvtColor(lane_image, cv2.COLOR_BGR2RGB)  # 视频色彩转换回RGB，这样才是现实的颜色
        showImage = QtGui.QImage(lane_image.data, lane_image.shape[1], lane_image.shape[0],
                                 QtGui.QImage.Format_RGB888)  # 把读取到的视频数据变成QImage形式
        self.showimage_2.setPixmap(QtGui.QPixmap.fromImage(showImage))  # 往显示视频的Label里 显示QImage

        image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)  # 视频色彩转换回RGB，这样才是现实的颜色
        showImage = QtGui.QImage(image.data, image.shape[1], lane_image.shape[0],
                                 QtGui.QImage.Format_RGB888)  # 把读取到的视频数据变成QImage形式
        self.showimage_3.setPixmap(QtGui.QPixmap.fromImage(showImage))  # 往显示视频的Label里 显示QImage


if __name__ == '__main__':  # 程序的入口
    app = QApplication(sys.argv)
    app.setStyleSheet(qdarkstyle.load_stylesheet())
    win = MymainWindow()
    win.show()
    sys.exit(app.exec_())